package H02.h2.Servlet;

import H02.h2.util.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/course")
public class courseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session=req.getSession();//获取当前会话
        String username =(String)session.getAttribute("username");//获取会话中的用户名

        if(username==null){//如果用户名为空，重定向回原本界面

            resp.sendRedirect("html/HomeWork02/h2/login.html");
            return;//结束方法

        }
        List<String> course=new ArrayList<>();//创建课程列表
        try(Connection conn= DBUtil.getConnection()){//使用DBUtil获取数据库连接
            //SQL查询，获取当前用户的所有课程
            String sql="SELECT register.dbo.course.course_name FROM course INNER JOIN " +
                    "users ON course.user_id = register.dbo.users.id WHERE users.username=?";
            PreparedStatement pstmt =conn.prepareStatement(sql);//创建pstmt
            pstmt.setString(1,username);
            ResultSet rs= pstmt.executeQuery();

            while(rs.next()){//遍历查询结果
                course.add(rs.getString("course_name"));//将课程名称添加到课程列表
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        req.setAttribute("course",course);//将课程表存入请求属性
        req.getRequestDispatcher("html/HomeWork02/h2/Courses.jsp").forward(req,resp);//将转发请求到Course.jsp
    }
}
